package com.skivingcloud.admin.sys.controller;

import com.mybatisflex.core.paginate.Page;
import com.skivingcloud.admin.conf.PasswordExpired;
import com.skivingcloud.admin.constants.Constant;
import com.skivingcloud.admin.security.SecurityUser;
import com.skivingcloud.admin.security.UserUtil;
import com.skivingcloud.admin.sys.entity.*;
import com.skivingcloud.admin.sys.service.*;
import com.skivingcloud.admin.utils.OtherUtil;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  控制层。
 *
 * @author skivingcloud
 * @since 2023-11-21
 */
@RestController
@Tag(name = "SysUserController", description = "用户管理API")
@RequestMapping("/sysUser")
public class SysUserController {
    
    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
    
    @Resource
    private SysUserService sysUserService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysStationService sysStationService;
    @Resource
    private SysUserStationService sysUserStationService;
    @Resource
    private PasswordExpired passwordExpired;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysUserMenuService sysUserMenuService;
    
    /**
     * 添加。
     *
     * @param sysUser 用户信息
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("/save")
    @Operation(summary="保存用户信息")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public ReturnT<Boolean> save(@Validated @RequestBody @Parameter(description="用户信息")SysUser sysUser) {
        try{
            sysUser.setId(UuidUtil.get32UUID());
            sysUser.setCreateUserId(UserUtil.getCurrentUser().getId());
            sysUser.setCreateTime(LocalDateTime.now());
            sysUser.setPassword(passwordEncoder.encode(passwordExpired.getDefaultValue()));
            return ReturnT.ok(sysUserService.save(sysUser));
        }catch(Exception e){
            log.error("新增用户信息失败", e);
            return ReturnT.error("新增用户信息失败");
        }
    }
    
    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @PostMapping("/remove/{id}")
    @Operation(summary="根据主键删除用户信息")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public ReturnT<Boolean> remove(@PathVariable("id") @Parameter(description="主键")Serializable id) {
        try{
            if(Constant.SUPER_ADMIN.equals(id)){
                return ReturnT.error("内置用户禁止删除！");
            }
            //逻辑删除
            SysUser sysUser = new SysUser();
            sysUser.setId(id.toString());
            sysUser.setStatus(Constant.USER_STATUS_DELETED);
            return ReturnT.ok(sysUserService.updateById(sysUser, true));
        }catch(Exception e){
            log.error("删除用户信息失败", e);
            return ReturnT.error("删除用户信息失败");
        }
    }
    
    /**
     * 根据主键更新。
     *
     * @param sysUser 用户信息
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PostMapping("/update")
    @Operation(summary="根据主键更新用户信息")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public ReturnT<Boolean> update(@Validated @RequestBody @Parameter(description="用户信息")SysUser sysUser) {
        try{
            return ReturnT.ok(sysUserService.updateById(sysUser));
        }catch(Exception e){
            log.error("保存用户信息失败", e);
            return ReturnT.error("保存用户信息失败！");
        }
    }
    
    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("/getInfo/{id}")
    @Operation(summary="根据主键获取用户信息")
    public ReturnT<SysUser> getInfo(@PathVariable("id") Serializable id) {
        return ReturnT.ok(sysUserService.getById(id));
    }
    
    /**
     * 获取当前登录用户信息。
     *
     * @return 详情
     */
    @GetMapping("/getInfoSession")
    @Operation(summary="获取当前登录用户信息")
    public ReturnT<SysUser> getInfoSession() {
        SecurityUser user = UserUtil.getCurrentUser();
        return ReturnT.ok(sysUserService.getUserIncludeById(user.getId()));
    }
    
    /**
     * 分页查询。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @PostMapping("/page")
    @Operation(summary="分页查询")
    public ReturnT<Page<SysUser>> page(@RequestBody @Parameter(description="分页信息")PageParameter<SysUser> parameter) {
        Page<SysUser> page = sysUserService.queryByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 根据主键重置密码。
     *
     * @param id 主键
     * @return {@code 0} 重置密码成功，{@code 500} 重置密码失败
     */
    @PostMapping("/resetPassword/{id}")
    @Operation(summary="根据主键重置密码")
    @PreAuthorize("hasAuthority('sys:user:resetPassword')")
    public ReturnT<String> resetPassword(@PathVariable("id") @Parameter(description="主键")Serializable id) {
        try{
            SysUser sysUser = sysUserService.getById(id);
            //生成一个带数字、字母的10位随机密码
            String newPassword = OtherUtil.generatePassword(10);
            sysUser.setPassword(passwordEncoder.encode(newPassword));
            sysUserService.updateById(sysUser);
            return ReturnT.ok(newPassword);
        }catch(Exception e){
            log.error("重置密码失败", e);
            return ReturnT.error("重置密码失败");
        }
    }
    
    /**
     * 根据用户id获取关联角色
     * @param id 用户id
     * @return 结果
     */
    @GetMapping("/getUserRolesByUserId/{id}")
    @Operation(summary="根据用户id获取关联角色")
    public ReturnT<Map<String, Object>> getUserRolesByUserId(@PathVariable("id") @Parameter(description="主键")String id) {
        try{
            SysUser sysUser = sysUserService.getById(id);
            List<SysRole> roles = sysRoleService.listByTenantId(sysUser.getTenantId());
            List<SysUserRole> userRoles = sysUserRoleService.listByUserId(id);
            Map<String, Object> map = new HashMap<>();
            map.put("roles", roles);
            map.put("userRoles", userRoles);
            return ReturnT.ok(map);
        }catch(Exception e){
            log.error("根据用户id获取关联角色失败", e);
            return ReturnT.error("根据用户id获取关联角色失败");
        }
    }
    
    /**
     * 设置用户角色
     * @param sysUser 用户
     * @return 修改结果
     */
    @Operation(summary="设置用户角色")
    @ApiResponse(responseCode = "2xx",description = "设置用户角色")
    @PostMapping("/setUserRolesByUserId")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public ReturnT<String> setUserRolesByUserId(@RequestBody SysUser sysUser){
        try{
            sysUserService.setUserRolesByUserId(sysUser);
            return ReturnT.ok("设置角色权限成功");
        }catch(Exception e){
            log.error("设置角色权限失败", e);
            return ReturnT.error("设置角色权限失败");
        }
    }
    
    /**
     * 根据用户id获取关联岗位
     * @param id 用户id
     * @return 结果
     */
    @GetMapping("/getUserStationTree/{id}")
    @Operation(summary="根据用户id获取关联岗位")
    public ReturnT<Map<String, Object>> getUserStationTree(@PathVariable("id") @Parameter(description="主键")String id) {
        try{
            SysUser sysUser = sysUserService.getById(id);
            List<SysOrg> orgs = sysStationService.treeByTenantId(sysUser.getTenantId());
            List<SysUserStation> userStations = sysUserStationService.listByUserId(id);
            Map<String, Object> map = new HashMap<>();
            map.put("stations", orgs);
            map.put("userStations", userStations.stream().map(SysUserStation::getStationId).toList());
            return ReturnT.ok(map);
        }catch(Exception e){
            log.error("根据用户id获取关联岗位失败", e);
            return ReturnT.error("根据用户id获取关联岗位失败");
        }
    }
    
    /**
     * 设置用户岗位
     * @param sysUser 用户
     * @return 修改结果
     */
    @Operation(summary="设置用户岗位")
    @ApiResponse(responseCode = "2xx",description = "设置用户岗位")
    @PostMapping("/setUserStationByUserId")
    @PreAuthorize("hasAuthority('sys:user:station')")
    public ReturnT<String> setUserStationByUserId(@RequestBody SysUser sysUser){
        try{
            sysUserService.setUserStationsByUserId(sysUser);
            return ReturnT.ok("设置岗位权限成功");
        }catch(Exception e){
            log.error("设置岗位权限失败", e);
            return ReturnT.error("设置岗位权限失败");
        }
    }
    
    /**
     * 根据租户和用户id加载资源树权限
     *
     * @param tenantId 租户ID
     * @param id 角色ID
     * @return 资源权限
     */
    @Operation(summary = "根据租户和用户id加载资源树权限", description = "根据租户和用户id加载资源树权限",
            parameters = {@Parameter(name = "tenantId, id", description = "租户id，用户id")})
    @ApiResponse(responseCode = "2xx",description = "根据租户和用户id加载资源树权限")
    @GetMapping("/getTenantUserResTree/{tenantId}/{id}")
    public ReturnT<Map<String, Object>> getTenantUserResTree(@PathVariable("tenantId") String tenantId, @PathVariable("id") String id){
        SecurityUser user = UserUtil.getCurrentUser();
        if (!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANT_ID)) {
            tenantId = user.getTenantId();
        }
        if (tenantId == null) {
            return ReturnT.error("租户不明确没数据");
        }
        List<SysMenu> list = sysMenuService.getTenantMenuList(tenantId);
        List<SysUserMenu> userResource = sysUserMenuService.listByUserId(id);
        Map<String, Object> res = new HashMap<>();
        res.put("tree", list);
        res.put("userResource", userResource.stream().map(SysUserMenu::getMenuId).toList());
        return ReturnT.ok(res);
    }
    
    /**
     * 设置用户资源
     * @param sysUser 用户
     * @return 修改结果
     */
    @Operation(summary="设置用户资源")
    @ApiResponse(responseCode = "2xx",description = "设置用户资源")
    @PostMapping("/setUserMenuByUserId")
    @PreAuthorize("hasAuthority('sys:user:menu')")
    public ReturnT<String> setUserMenuByUserId(@RequestBody SysUser sysUser){
        try{
            sysUserService.setUserMenuByUserId(sysUser);
            return ReturnT.ok("设置用户资源权限成功");
        }catch(Exception e){
            log.error("设置用户资源权限失败", e);
            return ReturnT.error("设置用户资源权限失败");
        }
    }
    
    /**
     * 根据岗位ID和用户ID查询用户姓名
     * @param parameter 参数
     * @return 逗号隔开的用户姓名
     */
    @PostMapping("/getUserNameByStationIdsAndUserIds")
    @Operation(summary="根据岗位ID和用户ID查询用户姓名")
    public ReturnT<String> getUserNameByStationIdsAndUserIds(@RequestBody UserQueryParameter parameter){
        return ReturnT.ok(sysUserService.getUserNameByStationIdsAndUserIds(parameter));
    }
    
    /**
     * 获取本租户下用户信息{key，value}
     * @return 用户信息
     */
    @Operation(summary = "查询本租户下用户信息", description = "查询本租户下用户信息")
    @ApiResponse(responseCode = "2xx",description = "查询本租户下用户信息")
    @GetMapping("/getAllUserBySelfTenant")
    public ReturnT<List<Map<String, Object>>> getAllUserBySelfTenant(){
        return ReturnT.ok(sysUserService.getAllUserBySelfTenant(UserUtil.getCurrentUser()));
    }
    
    /**
     * 获取本租户下用户ID
     * @return 用户信息
     */
    @Operation(summary = "查询本租户下用户ID", description = "查询本租户下用户ID")
    @ApiResponse(responseCode = "2xx",description = "查询本租户下用户ID")
    @GetMapping("/getAllUserIdsBySelfTenant")
    public ReturnT<List<String>> getAllUserIdsBySelfTenant(){
        return ReturnT.ok(sysUserService.getAllUserIdsBySelfTenant(UserUtil.getCurrentUser()));
    }
    
    /**
     * 根据租户获取关联岗位
     * @param tenantId 用户租户
     * @return 结果
     */
    @GetMapping("/getUserStationTreeByTenant/{tenantId}")
    @Operation(summary="根据租户id获取关联岗位")
    public ReturnT<List<SysOrg>> getUserStationTreeByTenant(@PathVariable("tenantId") @Parameter(description="主键")String tenantId) {
        try{
            List<SysOrg> orgList = sysStationService.treeByTenantId(tenantId);
            return ReturnT.ok(orgList);
        }catch(Exception e){
            log.error("根据租户id获取关联岗位失败", e);
            return ReturnT.error("根据租户id获取关联岗位失败");
        }
    }
    
    /**
     * 根据用户ID获取岗位集合
     * @param userId 用户ID
     * @return 结果
     */
    @GetMapping("/getStationListByUserId/{userId}")
    @Operation(summary="根据用户ID获取岗位集合")
    public ReturnT<List<SysStation>> getStationListByUserId(@PathVariable("userId") @Parameter(description="用户ID")String userId) {
        try{
            List<SysStation> stationList = sysStationService.getStationListByUserId(userId);
            return ReturnT.ok(stationList);
        }catch(Exception e){
            log.error("根据用户ID获取岗位集合", e);
            return ReturnT.error("根据用户ID获取岗位集合");
        }
    }
    
    /**
     * 根据用户ID获取岗位集合
     * @param userId 用户ID
     * @return 结果
     */
    @GetMapping("/getStationIdListByUserId/{userId}")
    @Operation(summary="根据用户ID获取岗位集合")
    public List<String> getStationIdListByUserId(@PathVariable("userId") @Parameter(description="用户ID")String userId) {
        try{
            List<SysStation> stationList = sysStationService.getStationListByUserId(userId);
            return stationList.stream().map(SysStation::getId).toList();
        }catch(Exception e){
            log.error("根据用户ID获取岗位集合失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据用户名查询用户信息
     * @param parameter 参数
     * @return 用户信息
     */
    @PostMapping("/queryUserByName")
    @Operation(summary="根据用户名查询用户信息")
    public ReturnT<List<SysUser>> queryUserByName(@RequestBody PageParameter<SysUser> parameter){
        if (parameter.getParam() == null || parameter.getParam().getStaffName().isBlank()) {
            return ReturnT.ok();
        }
        parameter.getParam().setTenantId(UserUtil.getCurrentUser().getTenantId());
        return ReturnT.ok(sysUserService.queryByPage(parameter).getRecords());
    }
}
